/*
 * i2c_eeprom.c
 *
 *  Created on: 04.04.2014
 *      Author: alexs
 */

//WP на 26-м PC3

#include "i2c_eeprom.h"
#include "usart.h"

#define WRITE_enable() DDRC|=(1<<PC3);
#define WRITE_disable() DDRC&=~(1<<PC3);
uint8_t TWI_last_error;

void i2c_eeprom_init(void) __attribute__ ((naked)) __attribute__ ((section (".init7")));
void i2c_eeprom_init() {
	/* I2C */
	TWSR=0;
	//		TWBR=33;
	TWBR=3; //Почти 400000 (363636)
	PORTC&=~(1<<PC3);
	//		DDRC|=(1<<PC3);
}


//static
uint8_t i2c_ee_read_tag(const uint16_t addr,uint8_t * buff) {
	uint16_t i;
	TWI_start();
	ifTWI(TW_START,0);
	TWI_send_data_nack(I2C_EEPROM|TW_WRITE);
	ifTWI(TW_MT_SLA_ACK,0);
	TWI_send_data_nack((uint8_t)((addr>>8)&0x1f)); //ADDR HI
	ifTWI(TW_MT_DATA_ACK,0);
	TWI_send_data_nack((uint8_t)(addr&0xff)); //ADDR LO
	ifTWI(TW_MT_DATA_ACK,0);
	TWI_restart();
	ifTWI(TW_REP_START,0);
	TWI_send_data_nack(I2C_EEPROM|TW_READ);
	ifTWI(TW_MR_SLA_ACK,0);
	for (i=0;i<(TAG_LEN-1);i++) {
		TWI_send_data_ack(0xFF);
		*buff++=TWDR;
	}
	TWI_send_data_nack(0xFF);
	*buff++=TWDR;
	TWI_stop();
	return TAG_LEN;
}

uint8_t i2c_ee_write_tag(const uint16_t addr,uint8_t * buff,const uint8_t len) {
	uint16_t i;
	uint16_t naddr=addr;
	WRITE_enable();
	for (i=0;i<len;i++) {
		TWI_start();
		ifTWI(TW_START,0);
		TWI_send_data_nack(I2C_EEPROM|TW_WRITE);
		ifTWI(TW_MT_SLA_ACK,0);
		TWI_send_data_nack((uint8_t)((naddr>>8)&0x1f)); //ADDR HI
		ifTWI(TW_MT_DATA_ACK,0);
		TWI_send_data_nack((uint8_t)(naddr&0xff)); //ADDR LO
		ifTWI(TW_MT_DATA_ACK,0);
		TWI_send_data_nack(*buff++);
		ifTWI(TW_MT_DATA_ACK,0);
		TWI_stop();

		do {
			TWI_start();
			ifTWI(TW_START,0);
			TWI_send_data_nack(I2C_EEPROM|TW_WRITE);
		}while (TWI_check(TW_MT_SLA_ACK));
		TWI_stop();
		naddr++;
	}
	WRITE_disable();

	return TAG_LEN;
}

void i2c_ee_clear_tags(uint8_t * local){
	uint16_t addr;
	const uint16_t tmp=0;

	for (addr=10;addr<EE_TOP;addr+=10){
		i2c_ee_write_tag(addr,(uint8_t *)&tmp,2);
	}
	i2c_ee_write_tag(0,local,TAG_LEN);
}
